var $tbody = $("#sample-table-1 tbody");
var allStation = [];

var nowdate = new Date(); 
var oneweekdate = new Date(nowdate-7*24*3600*1000);  
$("#beginDate").val(beginDate(oneweekdate));
$("#endDate").val(endDate(nowdate));

function beginDate(date) {
    return endDate(date);
};

function endDate(date) {
    return date.getFullYear() + "-" + ("0" + (date.getMonth() + 1)).slice(-2) + "-" + ("0" + date.getDate()).slice(-2);
};


getAllStation().done(function () {
// 初始化table
    $("#servicePersonalFinance_table").bootstrapTable({
        'url': '../finance/findServiceProvider',
        'cache':false,
        'queryParams': function (params) {
            params["stationId"] = $("#stationSelects").val();
            params["name"] = $("#inputStation").val();
            params["beginDate"] = $("#beginDate").val();
            params["endDate"] = $("#endDate").val();
            return params;
        },
        'toolbar': $('div[data-name="btnCtl"]'),
        'toolbarAlign': 'right',
        'striped': true,
        'sidePagination': 'server',
        'pagination': true,
        'pageSize': globalPageSize,
        'pageList': [],
        'clickToSelect': true,
        'singleSelect': true,
        'smartDisplay': true,
        'responseHandler': function (resb) {
            return {
                'total': resb.data.total,
                'rows': resb.data.rows
            }
        },
        'onCheck': function () {
            $("button[data-target='#updateModal'], button[data-target='#deleteModal']").removeAttr("disabled");
        },
        'onUncheck': function () {
            $("button[data-target='#updateModal'], button[data-target='#deleteModal']").attr("disabled", 'true');
        },
        'onPageChange': function () {
            if ($("#servicePersonalFinance_table").bootstrapTable('getSelections')[0]) {
                $("#servicePersonalFinance_table").bootstrapTable('uncheckBy', {
                    field: 'serviceProviderId',
                    values: [$("#servicePersonalFinance_table").bootstrapTable('getSelections')[0].serviceProviderId]
                });
            }

        },
        'columns': [{
            'checkbox': true,
            'class': 'hide'
        },
            {
                'field': 'serviceProviderId',
                'title': 'ID',
                'align': 'center',
                'class': 'hide'
            },
            {
                'field': 'stationName',
                'title': '车站名称',
                'width': 120,
                'align': 'center'              
            },
            {
                'field': 'serviceProviderName',
                'title': '服务人员',
                'width': 200,
                'align': 'center'

            },
            {
                'field': 'totalProductPrice',
                'title': '商品价格(元)',
                'align': 'center',
                'formatter': function (totalCost) {
                    if (totalCost == null) {
                        return totalCost = '无';
                    }
                    return totalCost.toFixed(2);
                }

            },
            {
                'field': 'totalDistributionCost',
                'title': '配送费(元)',
                'align': 'center',
                'formatter': function (totalCost) {
                    if (totalCost == null) {
                        return totalCost = '无';
                    }
                    return totalCost.toFixed(2);
                }

            },
            {
                'field': 'totalCost',
                'title': '总价(元)',
                'align': 'center',
                'formatter': function (totalCost) {
                    if (totalCost == null) {
                        return totalCost = '无';
                    }
                    return totalCost.toFixed(2);
                }

            },
            {
                'field': 'totalCount',
                'title': '总订单数(笔)',
                'width': 150,
                'align': 'center',


            },

            {
                'field': 'createDate',
                'title': '创建日期',
                'width': 150,
                'align': 'center',
                'sortable': true

            }
        ]
    });
});
/**
 * 服务人员查询ajax
 * @param name 请求查询的服务人员名称
 */
function financeQuery(stationId, name, beginDate, endDate) {
    if (($("#inputStation").val() == '')) {
        $('#servicePersonalFinance_table').bootstrapTable('refreshOptions', {pageNumber: 1, pageSize: globalPageSize});
    } else {
    	$.ajaxSetup({cache:false});
        $.ajax({
            type: "POST",
            url: "../finance/findServiceProvider",
            data: {
            	"stationId": stationId,
            	"serviceProviderName": name,
                'beginDate': beginDate,
                'endDate': endDate,
                "offset": 0,
                "limit": globalPageSize
            },
            dataType: 'json',
            //sidePagination: 'server',

            success: function (resb) {
                if (resb.data.totalElements != 0) {
                    $("#servicePersonalFinance_table").bootstrapTable('load', {
                        'total': resb.data.length,
                        'rows': resb.data.rows
                    });
                } else {
                    $("#servicePersonalFinance_table").bootstrapTable('removeAll');
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert(textStatus);
            }
        });
    }
    return false;
};

function exportExcel() {
    var $that = $(this),
        $inputs = $that.find("input[type=text]"),
        $stations = $(this).find('select[name="stationName"]'),
    stationId = $("#stationSelects").val(),
        name = $("#inputStation").val(),
        beginDate = $("#beginDate").val(),
        endDate = $("#endDate").val();
        console.log(stationId + beginDate);
    var url = '../finance/downloadServiceProvider.action?' + 'stationId=' + stationId + '&name=' + name +
        '&beginDate=' + beginDate + '&endDate=' + endDate;
    if ($("#downloadcsv")[0]) {
        $('#downloadcsv').attr('src', url);
    } else {
        $('body').append("<iframe id=\"downloadcsv\" style=\"display:none\"></iframe>");
        $('#downloadcsv').attr('src', url);
    }

};
$("#derive").on('click', function () {
    exportExcel()
});


/**
 * 角色操作(新增，更新，删除)
 * @param action [add/update/remove]
 * @param data
 *               [add/update 数据结构 {name: string, description: string, listAuthorityId: array} ]
 *               [delete 数据结构 {roleId: int}]
 * @param async/scync [default async]
 */
function serviceManagement(action, data, async) {
    var url = null;
    (async === false) ? async = false : async = true;
    if (action === 'add') {
        url = '../serviceProvider/add';
    } else if (action === 'update') {
        url = '../serviceProvider/update';
    } else {
        url = '../serviceProvider/delete';
    }
    ;
    return $.ajax({
        type: "POST",
        url: url,
        data: data,
        dataType: 'json',
        async: async,
        success: function (resb) {
            alert(resb.message);
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            // console.log(XMLHttpRequest, textStatus, errorThrown);
            alert(textStatus);
        }
    });
}


/*
 * 查询所有车站
 */
function getAllStation() {
    return $.ajax({
        type: "POST",
        url: '../railwayStation/getOnLineStation',
        dataType: 'json',
        error: function (request) {
            alert(request);
        },
        success: function (rs) {        	
            if (rs.success) {
                if (rs.data.length > 1) {
                    $(".selectAllStation").append("<option value=''>所有</option>");
                }
                ;
                for (var i = 0; i < rs.data.length; i++) {
                    $(".selectAllStation").append("<option value=" + rs.data[i].stationId + ">" + rs.data[i].stationName + "</option>");
                }
                ;
                allStation = rs;
            }
            ;
        }
    });
};

$(document).on('click','.spanIcons',function(){
	$('#inputStation').val("");
	if($('#inputStation').val() ==""){
		$('.spanIcons').removeClass('glyphicon glyphicon-remove');
	}
});
$("#inputStation").keyup(function(){
	if($('#inputStation').val() !=""){
		$('.spanIcons').addClass('glyphicon glyphicon-remove');
	}
	if($('#inputStation').val() ==""){
		$('.spanIcons').removeClass('glyphicon glyphicon-remove');
	}
})

/**
 * 查询表单提交
 */
$("#dataSearch").on('click', function () {
    var startTime = Date.parse(new Date($('#beginDate').val())),
        endTime = Date.parse(new Date($('#endDate').val()));
    if(startTime > endTime){
        alert('开始时间不能大于结束时间');
        return false;
    };
    return financeQuery($("#stationSelects").val(), $("#inputStation").val(), $("#beginDate").val(), $("#endDate").val());
});

$("#stationFormId").submit( function () {
    return financeQuery($("#stationSelects").val(), $("#inputStation").val(), $("#beginDate").val(), $("#endDate").val());
});

jQuery(function ($) {
    $('#id-disable-check').on('click', function () {
        var inp = $('#form-input-readonly').get(0);
        if (inp.hasAttribute('disabled')) {
            inp.setAttribute('readonly', 'true');
            inp.removeAttribute('disabled');
            inp.value = "This text field is readonly!";
        }
        else {
            inp.setAttribute('disabled', 'disabled');
            inp.removeAttribute('readonly');
            inp.value = "This text field is disabled!";
        }
    });
    $('.date-picker').datepicker({autoclose: true}).next().on(ace.click_event, function () {
        $(this).prev().focus();
    });
});